from django.shortcuts import render
from rest_framework import status, generics
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny, IsAuthenticated
from django.contrib.auth import authenticate, login, logout
from django.middleware.csrf import get_token
from .serializers import UserSerializer, UserLoginSerializer
from .models import User
import logging
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.contrib.auth.models import Group

logger = logging.getLogger(__name__)

# Create your views here.

@method_decorator(csrf_exempt, name='dispatch')
class UserRegisterView(generics.CreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [AllowAny]

    def create(self, request, *args, **kwargs):
        try:
            logger.debug(f"注册请求数据: {request.data}")
            serializer = self.get_serializer(data=request.data)
            
            if not serializer.is_valid():
                logger.error(f"验证错误: {serializer.errors}")
                return Response({
                    'status': 'error',
                    'message': '验证失败',
                    'errors': serializer.errors
                }, status=status.HTTP_400_BAD_REQUEST)
            
            user = serializer.save()
            
            # 根据用户类型添加到相应的用户组
            role = request.data.get('role', 'patient')  # 默认为患者角色
            group, _ = Group.objects.get_or_create(name=role)
            user.groups.add(group)
            
            logger.info(f"用户注册成功: {user.username}, 角色: {role}")
            
            return Response({
                'status': 'success',
                'message': '注册成功',
                'user': UserSerializer(user).data
            }, status=status.HTTP_201_CREATED)
            
        except Exception as e:
            logger.error(f"注册错误: {str(e)}")
            return Response({
                'status': 'error',
                'message': '注册失败',
                'error': str(e)
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class UserLoginView(APIView):
    permission_classes = [AllowAny]
    serializer_class = UserLoginSerializer

    def post(self, request):
        try:
            logger.debug(f"登录请求数据: {request.data}")
            serializer = self.serializer_class(data=request.data)
            
            if not serializer.is_valid():
                logger.error(f"登录验证错误: {serializer.errors}")
                return Response({
                    'status': 'error',
                    'message': '验证失败',
                    'errors': serializer.errors
                }, status=status.HTTP_400_BAD_REQUEST)
                
            username = serializer.validated_data['username']
            password = serializer.validated_data['password']
            user = authenticate(username=username, password=password)
            
            if user:
                if user.is_active:
                    login(request, user)
                    # 获取CSRF Token
                    csrf_token = get_token(request)
                    # 获取用户信息，包括用户组
                    user_data = UserSerializer(user).data
                    logger.info(f"用户登录成功: {username}, 角色: {user_data.get('groups', [])}")
                    return Response({
                        'status': 'success',
                        'message': '登录成功',
                        'user': user_data,
                        'csrfToken': csrf_token
                    })
                else:
                    logger.warning(f"禁用用户尝试登录: {username}")
                    return Response({
                        'status': 'error',
                        'message': '用户已被禁用'
                    }, status=status.HTTP_403_FORBIDDEN)
            else:
                logger.warning(f"登录失败: {username}")
                return Response({
                    'status': 'error',
                    'message': '用户名或密码错误'
                }, status=status.HTTP_401_UNAUTHORIZED)
                
        except Exception as e:
            logger.error(f"登录错误: {str(e)}")
            return Response({
                'status': 'error',
                'message': '登录失败',
                'error': str(e)
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class UserLogoutView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        try:
            username = request.user.username
            logout(request)
            logger.info(f"用户登出成功: {username}")
            return Response({
                'status': 'success',
                'message': '登出成功'
            })
        except Exception as e:
            logger.error(f"登出错误: {str(e)}")
            return Response({
                'status': 'error',
                'message': '登出失败',
                'error': str(e)
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class UserProfileView(generics.RetrieveUpdateAPIView):
    serializer_class = UserSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user

class GetCSRFToken(APIView):
    permission_classes = [AllowAny]
    
    def get(self, request):
        return Response({'csrfToken': get_token(request)})
